#! /usr/bin
#-*- coding:utf-8 -*-

__author__ = 'Michael'

import re
import urllib

class srcConverter:
    def __init__(self, log):
        self.__log = log

        self.__flagDic = {'*': "strong", "_": "em", "+": "ins", "-": "del"}
        self.__headPattern = re.compile(r'^h(?P<num>[123])\.\s+?(?P<title>.*)$')
        self.__stylePattern = re.compile(r'\s(?P<tag>[_*+-])(?P<content>.+?)\1\s')
        self.__urlPattern = re.compile(r'\b(?:https?|ftp|file)://[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]')
        self.__htmlTagPattern = re.compile(r'[<>"&]')
        self.__htmlTags = {"<": "&lt;", ">":"&gt;", "\"":"&quot;", "&": "&amp;"}
        pass

    def doConvert(self, src):
        """
        do wiki_syntax converts
        support:
        h1. h2. h3
        bold, italic, underline, strike
        """
        if not src:
            return src

        replace = src
        
        replace = re.sub(self.__htmlTagPattern, self.__htmlTag2Entity, replace)
        replace = re.sub(self.__stylePattern, self.__flag2tag, replace)
        replace = re.sub(self.__urlPattern, self.__url2link, replace)
        replace = re.sub(self.__headPattern, self.__title2tag, replace)

        replace = replace.replace("\n", "<br/>")

        #image replace required
        return replace

    def __htmlTag2Entity(self, matchObj):
        word = matchObj.group(0)
        return self.__htmlTags[word]

    def __url2link(self, matchObj):
        value = matchObj.group(0)
        return "&nbsp;<a href='%s' target='_blank'>%s</a>" % (value, value)

    def __flag2tag(self, matchObj):
        flag = matchObj.group("tag")
        content = matchObj.group("content")

        if not self.__flagDic.has_key(flag):
            print "WARN: no such flag %s" % flag
            return matchObj

        tag = self.__flagDic[flag]
        return "<%s>%s</%s>" % (tag, content, tag)
    

    def __title2tag(self, matchObj):
        num = matchObj.group("num")
        title = matchObj.group("title")

        return "<h%s>%s</h%s>" % (num, title, num)

